;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Account.MakeOutInvoice", [])
        .controller("MakeOutInvoiceCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "$timeout", '$filter',
            function ($scope, ybWidget, ybHttp, MESG_TYPE, UserContextService, $timeout, $filter) {
                var activeTitles = ['开票申请维护', '新增开票单', '编辑', '详情', '审核'];

                var statusObj = {
                    '0': '草稿',
                    '1': '已提交',
                    '2': '已完成',
                }
                var postFlagObj = {
                    '0': '未邮寄',
                    '1': '已邮寄',
                }
                var billingFlagObj = {
                    '0': '未开票',
                    '1': '已开票',
                }
                var needFlagObj = {
                    '0': '否',
                    '1': '是',
                }
                var repeal = {
                    '0': '未审核',
                    '1': '审核通过',
                    '2': '审核拒绝',
                    '3': '审核撤销',
                }                
                var payTypeObj = {
                    '1': '现金',
                    '2': '差价',
                    '3': '承兑',
                    '4': '融资',
                    '5': '调账',
                    '6': '返利',
                    '7': '服务费',
                    '8': '报告抵扣',
                    '9': '易贷',
                    '10': '三方转账',
                    '11': '电汇',
                    '12': '其他',
                }

                // 付款方式
                $scope.payTypeList = [{
                        id: 1,
                        name: "现金"
                    },
                    {
                        id: 2,
                        name: "差价"
                    },
                    {
                        id: 3,
                        name: "承兑"
                    },
                    {
                        id: 4,
                        name: "融资"
                    },
                    {
                        id: 5,
                        name: "调账"
                    },
                    {
                        id: 6,
                        name: "返利"
                    },
                    {
                        id: 7,
                        name: "服务费"
                    },
                    {
                        id: 8,
                        name: "报告抵扣"
                    },
                    {
                        id: 9,
                        name: "易贷"
                    },
                    {
                        id: 10,
                        name: "三方转账"
                    },
                    {
                        id: 11,
                        name: "电汇"
                    },
                    {
                        id: 12,
                        name: "其它"
                    },
                ];
                $scope.checkDate = function (item, start, end) {
                    if ((angular.isUndefined(item[start]) || !item[start]) && (angular.isUndefined(item[end]) || !item[end])) {
                        return;
                    }
                    if (!!item[start] && (angular.isUndefined(item[end]) || !item[end])) {
                        item[start] = ybWidget.FormatStartDate(item[start]);
                        return;
                    }
                    if ((angular.isUndefined(item[start]) || !item[start]) && !!item[end]) {
                        item[end] = ybWidget.FormatEndDate(item[end]);
                        return;
                    }
                    var tmpTime = item[start];
                    if (item[end] < item[start]) {
                        item[start] = ybWidget.FormatStartDate(item[end]);
                        item[end] = ybWidget.FormatEndDate(tmpTime);
                    } else {
                        item[start] = ybWidget.FormatStartDate(item[start]);
                        item[end] = ybWidget.FormatEndDate(item[end]);
                    }
                };
                $scope.auditType = 1;
                var btnPermissionCode = {
                    makeOutInvoiceAdd: window.ActionCode.makeOutInvoiceAdd, // 新建权限
                    makeOutInvoiceEdit: window.ActionCode.makeOutInvoiceEdit, // 编辑权限
                    makeOutInvoiceOneLevelAudit: window.ActionCode.makeOutInvoiceAudit, // 审核
                    // makeOutInvoiceOneLevelAudit: window.ActionCode.makeOutInvoiceAudit, ie浏览器strict 模式下不允许一个属性有多个定义
                    makeOutInvoicePrint: window.ActionCode.makeOutInvoicePrint, // 打印权限
                    makeOutInvoiceExport: window.ActionCode.makeOutInvoiceExport, // 导出权限
                    makeOutInvoiceFinish: window.ActionCode.makeOutInvoiceFinish, // 完成权限
                    makeOutInvoiceAuditOne: window.ActionCode.makeOutInvoiceAuditOne, // 一级审核
                    makeOutInvoiceAuditTwo: window.ActionCode.makeOutInvoiceAuditTwo, // 二级审核
                    makeOutInvoiceDelete: window.ActionCode.makeOutInvoiceDelete, // 删除
                    auditRepalOneBtn: window.ActionCode.auditRepalOneBtn, // 一级审核撤销
                    auditRepalTwoBtn: window.ActionCode.auditRepalTwoBtn, // 二级审核撤销
                };

                $scope.btnPermission = {};
                $scope.showDateStartCreateTime = false;
                $scope.showDateEndCreateTime = false;
                $scope.showDateStartFinishTime = false;
                $scope.showDateEndFinishTime = false;

                $scope.activeFlag = [true, false, false, false];
                $scope.markInfo = {
                    allChecked: false,
                    curRow: -1
                };
                $scope.pageInfo = {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                };
                $scope.tableConfig = {
                    scrollWidth: 1600,
                    tableCol: [{
                            name: "发票编号",
                            dataField: "invoiceNo",
                            width: 100,
                            toSort: false,
                            isShow: true,
                            type: "click",
                            clickFn: "viewDetail"
                        },
                        {
                            name: "客户编码",
                            dataField: "customerCode",
                            width: 80,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "客户名称",
                            dataField: "customerName",
                            width: 80,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "开票金额",
                            dataField: "amount",
                            width: 80,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "状态", // 0草稿，1已提交，2已完成
                            dataField: "statusF",
                            width: 100,
                            toSort: false,
                            isShow: true
                        },
                        /* wangcan:两级审核状态 */
                        {
                            name: "一级审核状态",
                            dataField: "oneLevelAuditStatusShow",
                            width: 100,
                            toSort: false,
                            isShow: !$scope.isNJ // 农机的不显示 
                        },
                        {
                            name: "二级审核状态",
                            dataField: "twoLevelAuditStatusShow",
                            width: 100,
                            toSort: false,
                            isShow: !$scope.isNJ // 农机的不显示 
                        },
                        {
                            name: "是否邮寄", //0未邮寄，1已邮寄
                            dataField: "postFlagF",
                            width: 80,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "客户是否需要发票", // 0否，1是
                            dataField: "needFlagF",
                            width: 80,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "纸质发票号",
                            dataField: "paperInvoiceNo",
                            width: 100,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "快递单号",
                            dataField: "trackingNo",
                            width: 100,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "创建人编号",
                            dataField: "createNo",
                            width: 80,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "创建人名称",
                            dataField: "createName",
                            width: 150,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "创建时间",
                            dataField: "createTimeF",
                            width: 130,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "修改人编号",
                            dataField: "updateNo",
                            width: 80,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "修改人名称",
                            dataField: "updateName",
                            width: 150,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "修改时间",
                            dataField: "updateTimeF",
                            width: 130,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "完成时间",
                            dataField: "finishTimeF",
                            width: 130,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "公司orgId",
                            dataField: "orgId",
                            width: 130,
                            toSort: false,
                            isShow: true
                        },
                        {
                            name: "一级审核人",
                            dataField: "oneLevelAuditor",
                            width: 130,
                            toSort: false,
                            isShow: !$scope.isNJ // 农机的不显示 
                        },
                        {
                            name: "二级审核人",
                            dataField: "twoLevelAuditor",
                            width: 130,
                            toSort: false,
                            isShow: !$scope.isNJ // 农机的不显示 
                        }
                    ]
                };
                $scope.dataList = [];
                $scope.toolbarConfig = {};

                /** 
                 * 列表页导出
                 **/
                $scope.exportParam = {
                    sectionUrl: ybHttp.RequestUrl("device", "/swyInvoice/export"), // 单个导出列表
                    sectionParam: {
                        ids: []
                    },
                    allUrl: ybHttp.RequestUrl("device", "/swyInvoice/exportAll") // 全部导出列表
                };

                /* 列表高级搜索查询条件配置 */
                $scope.condition = {};


                /** 
                 * 页面切换
                 **/
                $scope.changeTab = function (index) {
                    $scope.submitted = false;
                    $scope.activeFlag = [false, false, false, false];
                    $scope.activeFlag[index] = true;
                    if (index === 0) {
                        $scope.showDetail = false
                        $scope.showAuditDetail = false
                        $scope.activeTitle = ''
                    } else if (index === 4) {
                        $scope.showDetail = false
                        $scope.showAuditDetail = true
                        $scope.activeTitle = activeTitles[index]
                    } else {
                        $scope.showDetail = true
                        $scope.showAuditDetail = false
                        $scope.activeTitle = activeTitles[index]
                    }
                    switch (index) {
                        case 0: // 列表页面
                            $scope.markInfo.allChecked = false
                            getDataList();
                            break;
                        case 1: // 新增页面
                            $scope.orderObj = {
                                needFlag: 1, // 新增开票是否需要发票默认勾选是
                                settleType: 0 // 新增开票明细列表上选择框默认不勾选
                            };
                            $scope.addTableInfo.markInfo.allChecked = false
                            $scope.addTableInfo.dataList = []
                            break;
                        case 2: // 编辑页面
                            $scope.addTableInfo.markInfo.allChecked = true
                            break;
                        case 3: // 详情页面
                            break;
                        case 4: // 审核页面
                            break;
                        default:
                            break;
                    }
                };


                /** 
                 * 刷新列表数据
                 **/
                $scope.search = function (curpage) {
                    getDataList(curpage);
                };

                $scope.reset = function () {
                    $scope.condition = {};
                };


                /** 
                 * 配置表格列
                 **/
                $scope.switchToolbar = function (toolbar) {
                    if (!!$scope.toolbarConfig["show" + toolbar]) {
                        $scope.toolbarConfig["show" + toolbar] = false;
                        return;
                    }
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                };

                /** 
                 * 列表全选
                 **/
                $scope.selectAll = function () {
                    for (var i = 0; i < $scope.dataList.length; i++) {
                        $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                    }
                    getBillIds();
                };

                $scope.toSort = function (config, index) {
                    ybWidget.ToSort(config, index);
                };

                $scope.selectRow = function (index) {
                    $scope.markInfo.curRow = index
                };


                /** 
                 * 列表单选
                 **/
                $scope.selectSingle = function (item) {
                    var selectAll = false;
                    if (!item.isChecked) {
                        selectAll = false;
                    } else {
                        selectAll = checkAll($scope.dataList);
                    }
                    $scope.markInfo.allChecked = selectAll;
                    getBillIds();
                };

                function getBillIds() {
                    $scope.exportParam.sectionParam.ids = [];
                    angular.forEach($scope.dataList, function (item) {
                        if (!!item.isChecked) {
                            $scope.exportParam.sectionParam.ids.push(item.id);
                        }
                    });
                }

                function checkAll(list) {
                    var selectAll = false;
                    for (var i = 0, len = list.length; i < len; i++) {
                        if (!list[i].isChecked) {
                            selectAll = false;
                            break;
                        }
                        selectAll = true;
                    }
                    return selectAll;
                }

                function getDataList(curPage) {
                    $scope.markInfo.curRow = -1;

                    var service = "device",
                        reqUrl = "/swyInvoice/list",
                        param = {
                            pageSize: $scope.pageInfo.pageSize,
                            pageNum: $scope.pageInfo.curPage,
                            filters: angular.copy($scope.condition)
                        };

                    if (!!curPage) {
                        param.pageNum = $scope.pageInfo.curPage = curPage;
                    }

                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        // 列表中数据格式的转换
                        var df = "yyyy-MM-dd HH:mm:ss";
                        angular.forEach(resp.value.list, function (item) {
                            item.createTimeF = $filter("YbDate")(item.createTime, df);
                            item.updateTimeF = $filter("YbDate")(item.updateTime, df);
                            item.finishTimeF = $filter("YbDate")(item.finishTime, df);
                            item.statusF = statusObj[item.status];
                            item.oneLevelAuditStatusShow = $filter("ProgressStatus")(item.oneLevelAuditStatus, "audit");
                            item.twoLevelAuditStatusShow = $filter("ProgressStatus")(item.twoLevelAuditStatus, "audit");
                            item.postFlagF = postFlagObj[item.postFlag];
                            item.billingFlagF = billingFlagObj[item.billingFlag];
                            item.needFlagF = needFlagObj[item.needFlag];
                            item.isChecked = false;
                        });
                        $scope.pageInfo.totalRows = resp.value.total;
                        $scope.pageInfo.totalPages = resp.value.pages;
                        $scope.dataList = resp.value.list;
                    });

                }


                /** 
                 * 按钮权限获取
                 **/
                function setBtnPermission() {
                    for (var key in btnPermissionCode) {
                        $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                    }
                }

                /**
                 * 点击新建按钮，跳转到新增开票申请页面
                 **/
                $scope.addCheck = function () {
                    $scope.changeTab(1);
                };

                /** 
                 * 列表中编辑操作
                 **/
                $scope.edit = function (item) {
                    getDetailDataList(item.id);
                    $scope.changeTab(2)
                };

                /** 
                 * 列表中审核操作
                 **/
                $scope.audit = function (item, type) {
                    getDetailDataList(item.id);
                    if (type === 'one') {
                        $scope.auditType = 1
                    } else if (type === 'two') {
                        $scope.auditType = 2
                    }
                    $scope.changeTab(4)
                };


                /* 审核通过 */
                $scope.auditInvoice = function (type, id, message) {
                    var service = "device";
                    message = "审核意见测试";
                    if ($scope.auditType === 1) {
                        var reqUrl = "/swyInvoice/oneLevelAudit";
                        if (type === "refuse") {
                            reqUrl = "/swyInvoice/oneLevelRefuse";
                        }
                        var param = {
                            id: id,
                            oneLevelAuditOpinion: message
                        };
                        ybHttp.Post(service, reqUrl, param).then(function (resp) {
                            if (resp.code !== 0) {
                                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                                return;
                            }
                            if (type === "pass") {
                                ybWidget.ShowMessage("审核成功!");
                            }
                            ybWidget.ShowToaster('success', '操作成功');
                            $scope.changeTab(0);
                            $scope.orderObj.auditOpinion = "";
                        });
                    } else if ($scope.auditType === 2) {
                        var reqUrl = "/swyInvoice/twoLevelAudit";
                        if (type === "refuse") {
                            reqUrl = "/swyInvoice/twoLevelRefuse";
                        }
                        var param = {
                            id: id,
                            twoLevelAuditOpinion: message
                        };
                        ybHttp.Post(service, reqUrl, param).then(function (resp) {
                            if (resp.code !== 0) {
                                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                                return;
                            }
                            if (type === "pass") {
                                ybWidget.ShowMessage("审核成功!");
                            }
                            ybWidget.ShowToaster('success', '操作成功');
                            $scope.changeTab(0);
                            $scope.orderObj.auditOpinion = "";
                        });
                    }
                };

                /**
                 * 列表中编辑操作
                 **/
                $scope.finish = function (item) {
                    // 农机定制：农机 直接可以点击完成 
                    if ($scope.isNJ || (item.oneLevelAuditStatus == 1 && item.twoLevelAuditStatus == 1)) {
                        var param = {
                            id: item.id,
                            status: 2
                        }
                        updateData(param)
                    } else {
                        ybWidget.ShowMessage("请先完成一级审核和二级审核!");
                    }
                };

                /*跳转详情页 */
                $scope.tdClick = function (item, fnType) {
                    switch (fnType) {
                        case "viewDetail":
                            getDetailDataList(item.id);
                            $scope.changeTab(3);
                            break;
                        default:
                            break;
                    }
                };

                /** 
                 * 列表中打印操作
                 **/
                $scope.printBill = function (item) {
                    var param = {
                        printType: "MakeOutInvoice",
                        cusParam: { invoiceId: item.id }
                    };
                    ybWidget.SetIsPrintOrPreview(param);
                };

                /** 
                 * 列表中删除
                 **/
                $scope.delInvoice = function (id) {
                    ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                        var service = "device";
                        var reqUrl = "/swyInvoice/delete";
                        ybHttp.Post(service, reqUrl, {
                            invoiceId: id
                        }).then(function (resp) {
                            if (resp.code !== 0) {
                                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                                return;
                            }
                            ybWidget.ShowToaster('success', '操作成功');
                            getDataList();
                        });
                    })
                };
                /** 
                 * 撤销审核
                 **/
                $scope.auditRepal = function (item,type) {
                    ybWidget.ShowMessage("确定要撤销审核吗？", MESG_TYPE.Ask).then(function () {
                        var service = "device";
                        var reqUrl = type == 'one' ? '/swyInvoice/oneLevelRevoke': '/swyInvoice/twoLevelRevoke'
                        ybHttp.Post(service, reqUrl, {
                            id: item.id
                        }).then(function (resp) {
                            if (resp.code !== 0) {
                                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                                return;
                            }
                            ybWidget.ShowToaster('success', '操作成功');
                            getDataList();
                        });
                    })
                };
                /* 主列表的批量删除 */
                $scope.batchDel = function () {
                    var deleteList = [];
                    // 农机特殊处理：没有审核，未完成的均可删除
                    if ($scope.isNJ) {
                      for (const item of $scope.dataList) {
                        if (!item.isChecked) {
                          continue;
                        }

                        // 已完成 不可以删除
                        if (item.status == 2) {
                          deleteList = [];
                          break;
                        }
                        // 未完成 可以删除
                        deleteList.push(item.id);
                      }
                      
                      if (deleteList.length === 0) {
                          ybWidget.ShowMessage('请选择可删除的开票单（选择状态为未完成的开票单进行删除）', MESG_TYPE.Error);
                          return;
                      }
                    } else {
                      angular.forEach($scope.dataList, function (item) {
                          if (item.isChecked && item.oneLevelAuditStatus !== '1') {
                              deleteList.push(item.id);
                          } else if (item.isChecked && item.oneLevelAuditStatus === '1') {
                              deleteList = [];
                              return;
                          }
                      });
                      if (deleteList.length === 0) {
                          ybWidget.ShowMessage('请选择可删除的开票单（选择状态为未审核的开票单进行删除）', MESG_TYPE.Error);
                          return;
                      }
                    }
                    ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                        var service = "device";
                        var reqUrl = "/swyInvoice/batchDelete";
                        ybHttp.Post(service, reqUrl, deleteList).then(function (resp) {
                            if (resp.code !== 0) {
                                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                                return;
                            }
                            ybWidget.ShowToaster('success', '操作成功');
                            getDataList();
                        });
                    })
                };

                /*********************** 编辑、详情页开始 ***********************/
                function getDetailDataList(id) {
                    var service = "device",
                        reqUrl = "/swyInvoice/item",
                        param = {
                            invoiceId: id
                        };
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        $scope.hideAddPage = true
                        $scope.orderObj = resp.value
                        $scope.orderObj.needFlagF = needFlagObj[$scope.orderObj.needFlag]
                        $scope.orderObj.payTypeF = payTypeObj[$scope.orderObj.payType];
                        angular.forEach(resp.value.invoiceDetailList, function (item, idx) {
                            item.isChecked = true;
                            item.deliveryNo = item.deliveryNoteNo;
                            item.lineCode = item.rowNo || idx + 1;
                        });
                        angular.forEach(resp.value.invoiceDetailList,function(item){
                            item.deliveryQty = item.qty;//新增页面数量后端接口取deliveryQty的值，此接口为详情页面，取值为qty
                        })
                        $scope.addTableInfo.dataList = resp.value.invoiceDetailList;
                    });
                }


                function updateData(param) {
                    var service = "device";
                    var reqUrl = "/swyInvoice/update";
                    return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp.value, MESG_TYPE.Error);
                            return false;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.changeTab(0);
                    });
                }

                /*********************** 编辑、详情页结束 ***********************/

                $scope.saveData = function (valid, status) {
                    if (!valid) {
                        $scope.submitted = true;
                        return;
                    }
                    var param = angular.copy($scope.orderObj);
                    param.status = status;

                    param.invoiceDetailList = [];

                    angular.forEach($scope.addTableInfo.dataList, function (item) {
                        if (item.isChecked) {
                            param.invoiceDetailList.push({
                                deliveryNoteNo: item.deliveryNo, // 发货通知单
                                rowNo: item.lineCode, // 行号
                                materialsNo: item.materialsNo, // 零件号
                                qty: item.deliveryQty, // 数量
                                unit: item.unit, // 零件单位
                                price: item.price, // 单价
                                amount: item.amount, // 总价
                                materialsDes: item.materialsDes, // 零件中文名
                                deliveryCreateName: item.deliveryCreateName, // 申请人
                                deliveryRemark: item.deliveryRemark, // 备注
                                sapOutBill: item.sapOutBill, // 外向交货单
                                sapSaleOrder: item.sapSaleOrder, // 采购订单
                                materialsPZNo: item.materialsPZNo, // 零件凭证号
                            });
                        }
                    });
                    if (param.invoiceDetailList.length === 0) {
                        ybWidget.ShowMessage('请先选择开票明细', MESG_TYPE.Warn);
                        return;
                    }
                    if ($scope.activeFlag[1]) {
                        addData(param)
                    } else if ($scope.activeFlag[2]) {
                        updateData(param)
                    }
                }



                /**
                 * ***************************************** 新增 开始 *****************************************
                 */
                $scope.addPageInfo = {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                };


                $scope.selectDealer = function () {
                    var param = {
                        name: "客户",
                        type: "dealer"
                    };
                    ybWidget.SingleSelector(param).then(function (data) {
                        $scope.orderObj.customerCode = data.dealerCode;
                        $scope.orderObj.customerName = data.companyName;
                        if (!$scope.orderObj.customerCode && $scope.isSCH) {
                            $scope.orderObj.customerName = ''
                             ybWidget.ShowMessage('客户编号为空,请填写客户编号', MESG_TYPE.Error);
                        }
                        $scope.orderObj.orgId = data.dealerOrgId;
                        getDeliveryNosList();
                    })
                };

                function getDeliveryNosList() {
                    var service = "device",
                        reqUrl = "/swyInvoice/listDeliveryNos",
                        param = {
                            filters: $scope.orderObj.orgId,
                            pageNum: $scope.addPageInfo.curPage,
                            pageSize: $scope.addPageInfo.pageSize
                        };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        $scope.hideAddPage = false
                        $scope.addTableInfo.markInfo.allChecked = false
                        angular.forEach(resp.value.list, function (item, idx) {
                            item.isChecked = false;
                            item.lineCode = idx + 1;
                        });
                        // resp.value.list[0].qty =7878787;
                        $scope.addPageInfo.totalRows = resp.value.total;
                        $scope.addPageInfo.totalPages = resp.value.pages;
                        $scope.addTableInfo.dataList = resp.value.list;
                    });
                }

                $scope.addPageSearch = function () {
                    getDeliveryNosList()
                }

                function addData(param) {
                    var service = "device";
                    var reqUrl = "/swyInvoice/save";

                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.changeTab(0);
                    });
                };


                /* 新建页面上开票明细列表 */
                $scope.addTableInfo = {
                    markInfo: {
                        allChecked: false,
                        curRow: -1
                    },
                    tableConfig: {
                        scrollWidth: 750,
                        tableCol: [{
                                name: "行号",
                                dataField: "lineCode",
                                width: 60,
                                isShow: true
                            },
                            {
                                name: "发货通知单",
                                dataField: "deliveryNo",
                                width: 140,
                                isShow: true,
                            },
                            {
                                name: "零件号",
                                dataField: "materialsNo",
                                width: 100,
                                isShow: true
                            },
                            {
                                name: "零件中文名",
                                dataField: "materialsDes",
                                width: 100,
                                isShow: true
                            },
                            {
                                name: "零件分类",
                                dataField: "materialsType",
                                width: 100,
                                isShow: true
                            },                            
                            {
                                name: "数量",
                                dataField: "deliveryQty",
                                width: 130,
                                isShow: true
                            },
                            {
                                name: "零件单位",
                                dataField: "unit",
                                width: 100,
                                isShow: true
                            },
                            {
                                name: "单价",
                                dataField: "price",
                                width: 100,
                                isShow: true
                            },
                            {
                                name: "总价",
                                dataField: "amount",
                                width: 100,
                                isShow: true
                            },
                            {
                                name: "申请人",
                                dataField: "deliveryCreateName",
                                width: 100,
                                isShow: true
                            },
                            {
                                name: "备注",
                                dataField: "deliveryRemark",
                                width: 100,
                                isShow: true
                            },
                            {
                                name: "SAP外向交货单",
                                dataField: "sapOutBill",
                                width: 100,
                                isShow: true
                            },
                            {
                                name: "SAP销售订单",
                                dataField: "sapSaleOrder",
                                width: 100,
                                isShow: true
                            },
                            {
                                name: "零件凭证",
                                dataField: "materialsPZNo",
                                width: 100,
                                isShow: true
                            },
                        ]
                    },
                    dataList: [],
                    /** 
                     * 开票明细列表排序
                     **/
                    toSort: function (config, index) {
                        ybWidget.ToSort(config, index);
                    },

                    /** 
                     * 行选择
                     **/
                    selectRow: function (index) {
                        $scope.addTableInfo.markInfo.curRow = index
                    },

                    /** 
                     * 新增开票明细列表全选
                     **/
                    selectAll: function () {
                        for (var i = 0; i < $scope.addTableInfo.dataList.length; i++) {
                            $scope.addTableInfo.dataList[i].isChecked = $scope.addTableInfo.markInfo.allChecked;
                        }
                        if ($scope.addTableInfo.dataList.length > 0) {
                            countTotalPrice();
                        }
                    },
                    /**
                     * 新增开票明细列表单选
                     **/
                    selectSingle: function (item) {
                        var selectAll = false;
                        if (!item.isChecked) {
                            selectAll = false;
                        } else {
                            selectAll = checkAll($scope.addTableInfo.dataList);
                        }
                        $scope.addTableInfo.markInfo.allChecked = selectAll;
                        countTotalPrice();
                    },
                };


                // function clearTotalPrice() {
                //     $scope.orderObj.totalPrice = "";
                //     $scope.orderObj.discountPrice = "";
                //     $scope.orderObj.realPrice = "";
                //     $scope.orderObj.advancePayPrice = "";
                // }

                function countTotalPrice() {
                    var totalPrice = null;
                    angular.forEach($scope.addTableInfo.dataList, function (item) {
                        if (item.isChecked) {
                            item.checkPrice = item.amount;
                            totalPrice = ybWidget.Plus(totalPrice, item.amount);
                        } else {
                            item.checkPrice = null;
                        }
                    });
                    $scope.orderObj.amount = Number(totalPrice).toFixed(2);
                }

                // 预收款价格扣减变化
                // $scope.prePayPriceChange = function () {
                //     var prePayPrice = Number($scope.orderObj.prePayPrice) || 0;
                //     var advancePayPrice = Number($scope.orderObj.advancePayPrice) || 0;
                //     // 如果预收款扣减大于客户的预收款额度 则取额度的值
                //     if (advancePayPrice > prePayPrice) {
                //         $scope.orderObj.advancePayPrice = prePayPrice;
                //     }
                //     countRealPrice();
                // };

                // function countRealPrice() {
                //     var totalPrice = Number($scope.orderObj.totalPrice) || 0,
                //         discountPrice = Number($scope.orderObj.discountPrice) || 0;
                //     var advancePayPrice = Number($scope.orderObj.advancePayPrice) || 0;
                //     if (discountPrice > totalPrice) {
                //         $scope.orderObj.discountPrice = discountPrice = totalPrice;
                //         $scope.orderObj.advancePayPrice = advancePayPrice = 0;
                //     }
                //     var restPrice = ybWidget.Minus(totalPrice, discountPrice);
                //     if (advancePayPrice > restPrice) {
                //         $scope.orderObj.advancePayPrice = advancePayPrice = restPrice;
                //     }
                //     var plus = ybWidget.Plus(discountPrice, advancePayPrice);
                //     $scope.orderObj.realPrice = ybWidget.Minus(totalPrice, plus);
                // }
                /**
                 * ***************************************** 新增 结束 *****************************************
                 */

                (function () {
                    getDataList(1);
                    UserContextService.SetBtnPermission(setBtnPermission);
                })();
            }
        ]);
})(window, window.angular);